
using AutoMapper;
using Coldairarrow.Util;
using DTO;
using DTO.Output;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Model;
using NPOI.SS.Formula.Functions;
using NPOI.XSSF.UserModel;
using SqlSugar;
using System.Collections.Generic;
using Util;

namespace API.Controllers
{
    public class MealReportingController : BaseController
    {
        Repository<tMealReporting> _MealReporting;
        Repository<tAutoMealReporting> _AutoM;
        Repository<tConfiguration> _configuration;
        Repository<tSignIn> _SignIn;
        Repository<tCanteenMenu> _CanteenMenu;
        readonly IMapper _mapper;
        ISqlSugarClient _db;
        private readonly IWebHostEnvironment _webHostEnvironment;
        public MealReportingController(Repository<tMealReporting> MealReporting, IMapper mapper, Repository<tConfiguration> configuration, Repository<tSignIn> signIn, Repository<tAutoMealReporting> mealReporting, ISqlSugarClient db, Repository<tCanteenMenu> canteenMenu, IWebHostEnvironment webHostEnvironment)
        {
            _MealReporting = MealReporting;
            _mapper = mapper;
            _configuration = configuration;
            _SignIn = signIn;
            _AutoM = mealReporting;
            _db = db;
            _CanteenMenu = canteenMenu;
            _webHostEnvironment = webHostEnvironment;
        }

        /// <summary>
        /// 员工手动报餐
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<string>> EReporting(EReportingInput input)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {

                var model = _MealReporting.GetFirst(x => x.FEID == input.EID && x.FEName == input.EName && x.FRTime == input.RTime && x.FMType == input.MType && x.FDeleted == false);
                if (model != null)
                {
                    return result.Error("您已经报过餐了!");
                }
                string str = string.Empty;
                if (input.MType == 1)
                {
                    str = _configuration.GetSingle(x => x.FCode == "Lunch").FCodeValue;
                }
                else if (input.MType == 2)
                {
                    str = _configuration.GetSingle(x => x.FCode == "Dinner").FCodeValue;
                }
                var lastTime = DateTime.Parse(DateTime.Now.Date.ToShortDateString() + " " + str);
                bool IsOverTime = DateTime.Now > lastTime ? true : false;
                model = new tMealReporting()
                {
                    Id=IdHelper.GetId(),
                    FEID = input.EID,
                    FEName = input.EName,
                    FEEngName = input.EEngName,
                    FDeptName = input.DeptName,
                    FMType = input.MType,
                    FRTime = input.RTime,
                    FIsOverTime = IsOverTime,
                    FReportingType = 2,
                    CreatorId = CurrentUserId,
                    CreateTime = DateTime.Now,
                    FDeleted = false,
                    FWorkOver = input.WorkOver,
                    FIsOdd = false
                };
                await _MealReporting.InsertAsync(model);
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("MealReportingController-EReporting:" + ex);
                return result.Exception();
            }
        }
        /// <summary>
        /// 切换是否加班报餐
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<string>> UpdateOverTime(UpdateOverTimeInput input)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                var model = _MealReporting.GetFirst(x => x.FEID == input.EID && x.FDeleted == false && x.FRTime == input.RTime && x.FMType == 2);
                if (model == null)
                    return result.Error("请先报餐!");
                model.FWorkOver = input.WorkOver;
                await _MealReporting.UpdateAsync(model);
                return result.Success("切换成功!");
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("MealReportingController-UpdateOverTime:" + ex);
                return result.Exception();
            }
        }

        /// <summary>
        /// 员工取消报餐
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<string>> ECancelReporting(ECancelReportingInput input)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                var model = _MealReporting.GetFirst(x => x.FEID == input.EID && x.FEName == input.EName && x.FRTime == input.RTime && x.FMType == input.MType && !x.FDeleted);
                if (model == null)
                {
                    return result.Error("您还没有报餐呢!");
                }
                var sign = _SignIn.GetFirst(x => x.FRId == model.Id);
                if (sign != null)
                {
                    return result.Error("已用餐不允许取消!");
                }
                model.FCancellation = true;
                model.FCancelTime = DateTime.Now;
                model.FCancelReason = input.CancelReason;
                model.FDeleted = true;
                await _MealReporting.UpdateAsync(model);
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("MealReportingController-ECancelReporting:" + ex);
                return result.Exception();
            }
        }
        /// <summary>
        /// 员工开启/关闭自动报餐
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<string>> ChangeAutoReport(OpenAutoReportInput input)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                var model = _AutoM.GetFirst(c => c.FEId == input.EID && c.FEName == input.EName && c.FAutoReportingType == input.MType);
                if (model == null)
                {
                    model = new tAutoMealReporting()
                    {
                        FAutoReportingType = input.MType,
                        FEId = input.EID,
                        FEName = input.EName,
                        FIsOpen = input.MType == 1,
                        FOpenTime = DateTime.Now,
                        CreatorId = CurrentUserId,
                        CreateTime = DateTime.Now,
                        Id=IdHelper.GetId()

                    };
                    await _AutoM.InsertAsync(model);
                    return result.Success();
                }
                else
                {
                    model.FIsOpen = input.IsOpen;
                    model.FCloseTime = input.IsOpen ? DateTime.MinValue : DateTime.Now;
                    await _AutoM.UpdateAsync(model);
                    return result.Success();
                }
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("MealReportingController-OpenAutoReport:" + ex);
                return result.Exception();
            }
        }
        /// <summary>
        /// 获取员工自动报餐情况
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultMsg<GetAutoReportByUserOutput>> GetAutoReportByUser(int EID)
        {
            ResultMsg< GetAutoReportByUserOutput> result = new ResultMsg<GetAutoReportByUserOutput>();
            try
            {
                GetAutoReportByUserOutput model = new GetAutoReportByUserOutput();
                model.EID = EID;
                var list = await _AutoM.GetListAsync(x => x.FEId == EID.ToString());
                if (list.Count > 0)
                {
                    var m = list.Where(x => x.FAutoReportingType == 1).FirstOrDefault();
                    if (m != null)
                    {
                        model.autoLunch = m.FIsOpen;
                    }
                    else
                    {
                        model.autoLunch = false;
                    }
                    m = list.Where(x => x.FAutoReportingType == 2).FirstOrDefault();
                    if (m != null)
                    {
                        model.autoDinner = m.FIsOpen;
                    }
                    else
                    {
                        model.autoDinner = false;
                    }
                }
                return result.Success(model);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("MealReportingController-GetAutoReportByUser:" + ex);
                return result.Exception();
            }
        }
        /// <summary>
        /// 报餐情况统计
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<List<RepstatisticsDao>>> Repstatistics(RepstatisticsInput input)
        {
            ResultMsg<List<RepstatisticsDao>> result = new ResultMsg<List<RepstatisticsDao>>();
            try
            {
                var list = _MealReporting.AsQueryable().GroupBy(t => new { t.FRTime, t.FMType }).Where(c => c.FRTime >= input.StartDate && c.FRTime <= input.EndDate && c.FDeleted == false && !c.FIsOdd).OrderBy(c => c.FRTime).Select(it => new
                RepstatisticsDao
                {
                    rdate = it.FRTime.ToString("yyyy-MM-dd"),
                    num = SqlFunc.AggregateCount(it.Id),
                    type = it.FMType == 1 ? "午餐" : "晚餐"
                }).ToList();
                return result.Success(list, list.Count);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("MealReportingController-Repstatistics:" + ex);
                return result.Exception();
            }
        }

        /// <summary>
        /// 报餐人员用餐情况统计表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<ResultMsg<List<RepEdtstatisticsOutput>>> RepEdtstatistics(RepstatisticsInput input)
        {
            ResultMsg<List<RepEdtstatisticsOutput>> result = new ResultMsg<List<RepEdtstatisticsOutput>>();
            try
            {
                var exp = Expressionable.Create<tMealReporting>();
                exp.And(m => m.FDeleted == false && m.FRTime >= input.StartDate && m.FRTime <= input.EndDate);
                if (!string.IsNullOrWhiteSpace(input.Name))
                {
                    exp.And(m => m.FEName.Contains(input.Name));
                }
                if (input.Type != 0)
                {
                    exp.And(m => m.FMType == input.Type);
                }
                var list = _db.Queryable<tMealReporting>()
                     .LeftJoin<tSignIn>((m, s) => m.FEID == s.FEId && m.Id == s.FRId)
                     .Where(exp.ToExpression()).Distinct()
                     .OrderByDescending((m, s) => s.CreateTime)
                     .Select((m, s) => new RepEdtstatisticsOutput
                     {
                         RepTime = m.FRTime.ToString("yyyy-MM-dd"),
                         Rtime = m.CreateTime,
                         Stime = s.CreateTime,
                         Type = m.FMType == 1 ? "午餐" : "晚餐",
                         Name = m.FEName,
                         IsCancel = m.FCancellation ? "是" : "否",
                         CTime = m.FCancelTime,
                         CancelReason = m.FCancelReason,
                     }).ToList();
                if (input.EatType == 1)
                {
                    list = list.Where(x => x.Stime == null).ToList();
                }
                else if (input.EatType == 2)
                {
                    list = list.Where(x => x.Stime != null).ToList();
                }
                var count = list.Count;
                return result.Success(list.Skip((input.PageNum - 1) * input.PageSize).Take(input.PageSize).ToList(), count);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("MealReportingController-RepEdtstatistics:" + ex);
                return result.Exception();
            }
        }
        /// <summary>
        /// 用餐情况统计表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<List<EdtstatisticsOutput>>> Edtstatistics(RepstatisticsInput input)
        {
            ResultMsg<List<EdtstatisticsOutput>> result = new ResultMsg<List<EdtstatisticsOutput>>();
            try
            {
                var exp = Expressionable.Create<tSignIn>();
                if (!string.IsNullOrWhiteSpace(input.Name))
                {
                    exp.And(m => m.FEName.Contains(input.Name));
                }
                exp.And(x => x.CreateTime >= input.StartDate && x.CreateTime <= input.EndDate);
                var count = await _SignIn.CountAsync(exp.ToExpression());
                var signList = (await _SignIn.GetListAsync(exp.ToExpression())).OrderByDescending(c => c.CreateTime).ToList();
                List<EdtstatisticsOutput> list = new List<EdtstatisticsOutput>();
                var exp2 = Expressionable.Create<tMealReporting>();

                var mealList = await _MealReporting.GetListAsync(exp2.ToExpression());
                EdtstatisticsOutput dao = new EdtstatisticsOutput();
                foreach (var item in signList)
                {
                    dao = new EdtstatisticsOutput();
                    dao.Rep = item.FRId == "0" ? "否" : "是";
                    if (item.FRId.Length > 1)
                    {
                        var FType = mealList.Where(x => x.Id == item.FRId).FirstOrDefault()?.FMType;
                        dao.FType = FType == 1 ? "午餐" : "晚餐";
                    }
                    else
                    {
                        var hour = item.CreateTime.Hour;
                        if (hour >= 11 && hour <= 14)
                        {
                            dao.FType = "午餐";
                        }
                        else if (hour >= 17 && hour <= 20)
                        {
                            dao.FType = "晚餐";
                        }
                    }
                    dao.Name = item.FEName;
                    dao.STime = item.CreateTime;
                    dao.RDate = item.CreateTime.ToString("yyyy-MM-dd");
                    list.Add(dao);
                }
                if (input.EatType == 1)
                {
                    list = list.Where(x => x.Rep == "是").ToList();
                }
                else if (input.EatType == 2)
                {
                    list = list.Where(x => x.Rep == "否").ToList();
                }
                if (input.Type != 0)
                {
                    string FType = input.Type == 1 ? "午餐" : "晚餐";
                    list = list.Where(x => x.FType == FType).ToList();
                }
                count = list.Count();
                list = list.Skip((input.PageNum - 1) * input.PageSize).Take(input.PageSize).ToList();
                return result.Success(list, count);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("MealReportingController-Edtstatistics:" + ex);
                return result.Exception();
            }
        }
        /// <summary>
        /// 初始化新员工自动报餐
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<string>> NewStaffAutoReport(newStaffAutoReportInput input)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                tAutoMealReporting auto = new tAutoMealReporting();
                var model = await _AutoM.GetFirstAsync(x => x.FEId == input.UserId.ToString() && x.FAutoReportingType == 1);
                if (model == null)
                {
                    auto=new tAutoMealReporting();
                    auto.FAutoReportingType = 1;
                    auto.FEId = input.UserId.ToString();
                    auto.FEName = input.UserName;
                    auto.FEEngName = input.UserEngName;
                    auto.FIsOpen = true;
                    auto.FOpenTime = DateTime.Now;
                    auto.FCloseTime = DateTime.MinValue;
                    auto.FDeleted = false;
                    InitEntity(auto);
                   await _AutoM.InsertAsync(auto);
                }
                model = await _AutoM.GetFirstAsync(x => x.FEId == input.UserId.ToString() && x.FAutoReportingType == 2);
                if (model == null)
                {
                    auto = new tAutoMealReporting();
                    auto.FAutoReportingType = 2;
                    auto.FEId = input.UserId.ToString();
                    auto.FEName = input.UserName;
                    auto.FEEngName = input.UserEngName;
                    auto.FIsOpen = false;
                    auto.FOpenTime = DateTime.Now;
                    auto.FCloseTime = DateTime.MinValue;
                    auto.FDeleted = false;
                    InitEntity(auto);
                    await _AutoM.InsertAsync(auto);
                }
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("MealReportingController-NewStaffAutoReport:" + ex);
                return result.Exception();
            }
        }
        /// <summary>
        /// 自动报餐
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<ResultMsg<string>> AutoReport()
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                List<tAutoMealReporting> autoList = new List<tAutoMealReporting>();
                DateTime dt = DateTime.Now;
                //获取当天菜单,有菜单才自动报餐
                var meen = await _CanteenMenu.GetFirstAsync(x => x.FMTime == dt.Date && x.FMType == 1);
                if (meen != null && !string.IsNullOrEmpty(meen.FMName) && !string.IsNullOrEmpty(meen.FMName2) && !string.IsNullOrEmpty(meen.FMName3))
                {
                    autoList = await _AutoM.GetListAsync(x => x.FAutoReportingType == 1 && x.FIsOpen);
                    if (autoList != null && autoList.Count() > 0)
                    {
                        foreach (var item in autoList)
                        {
                            if (await _MealReporting.GetFirstAsync(x => x.FEID == item.FEId && x.FMType == 1 && x.FRTime == dt.Date && x.FDeleted == false) == null)
                            {
                                await _MealReporting.InsertAsync(new tMealReporting
                                {
                                    Id=IdHelper.GetId(),
                                    FMType = 1,
                                    FEID = item.FEId,
                                    FEName = item.FEName,
                                    FEEngName = item.FEEngName,
                                    FRTime = DateTime.Now.Date,
                                    FWorkOver = false,
                                    FCancellation = false,
                                    FCancelReason = "",
                                    FDeleted = false,
                                    FIsOverTime = false,
                                    FReportingType = 1,
                                    CreateTime = DateTime.Now,
                                    CreatorId = CurrentUserId,
                                    FIsOdd = false
                                });
                            }
                        }
                    }
                }
                meen = _CanteenMenu.GetFirstAsync(x => x.FMTime == dt.Date && x.FMType == 2).Result;
                if (meen != null && !string.IsNullOrEmpty(meen.FMName) && !string.IsNullOrEmpty(meen.FMName2) && !string.IsNullOrEmpty(meen.FMName3))
                {
                    autoList = await _AutoM.GetListAsync(x => x.FAutoReportingType == 2 && x.FIsOpen);
                    if (autoList != null && autoList.Count() > 0)
                    {
                        foreach (var item in autoList)
                        {
                            if ((await _MealReporting.GetFirstAsync(x => x.FEID == item.FEId && x.FMType == 2 && x.FRTime == DateTime.Now.Date && x.FDeleted == false) == null))
                            {
                                await _MealReporting.InsertAsync(new tMealReporting
                                {
                                    Id=IdHelper.GetId(),
                                    FMType = 2,
                                    FEID = item.FEId,
                                    FEName = item.FEName,
                                    FEEngName = item.FEEngName,
                                    FRTime = DateTime.Now.Date,
                                    FWorkOver = false,
                                    FCancellation = false,
                                    FCancelReason = "",
                                    FDeleted = false,
                                    FIsOverTime = false,
                                    FReportingType = 1,
                                    CreateTime = DateTime.Now,
                                    CreatorId = CurrentUserId,
                                    FIsOdd = false
                                });
                            }
                        }
                    }
                }
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("MealReportingController-RepEdtstatistics:" + ex);
                return result.Exception();
            }
        }

        /// <summary>
        /// 获取当天报餐人员
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<List<string>>> GetStaffByDate(GetStaffByDateInput input)
        {
            ResultMsg<List<string>> result = new ResultMsg<List<string>>();
            try
            {
               
                var list = _MealReporting.GetList(x => x.FMType == input.RType && x.FRTime == DateTime.Parse(input.RDate) && x.FDeleted == false).Select(c => c.FEName).ToList();
                return result.Success(list);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("MealReportingController-GetStaffByDate:" + ex);
                return result.Exception();
            }
        }
        /// <summary>
        /// 晚餐费用报表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<List<GetDinnerCostReportOutput>>> GetDinnerCostReport(GetDinnerCostReportInput input)
        {
            ResultMsg<List<GetDinnerCostReportOutput>> result = new ResultMsg<List<GetDinnerCostReportOutput>>();
            try
            {
                Common commonInstance = new Common(_db); // 使用db实例化Common类
                DateTime startTime = input.month;
                DateTime endTime = startTime.AddMonths(1).AddDays(-1);
                var exp = Expressionable.Create<tMealReporting>();
                exp.And(x => x.FRTime >= startTime && x.FRTime <= endTime && x.FDeleted == false && x.FMType == 2 && !x.FIsOdd);
                if (!string.IsNullOrWhiteSpace(input.EName))
                {
                    exp.And(x => x.FEEngName.Contains(input.EName));
                }
                var list = _MealReporting.GetList(exp.ToExpression());
                var reportList = list.Select(c => new GetDinnerCostReportOutput
                {
                    eId = c.FEID,
                    //eName = !string.IsNullOrWhiteSpace(c.EEngName) ? c.EName + "(" + c.EEngName + ")" : c.EName,
                    eName = c.FEName,
                    eEngName = c.FEEngName,
                    deptName = c.FDeptName
                }).ToList();
                foreach (var item in reportList)
                {
                    fill(item, 1);
                    fill(item, 2);
                    fill(item, 3);
                    fill(item, 4);
                    fill(item, 5);
                    fill(item, 6);
                    fill(item, 7);
                    fill(item, 8);
                    fill(item, 9);
                    fill(item, 10);
                    fill(item, 11);
                    fill(item, 12);
                    fill(item, 13);
                    fill(item, 14);
                    fill(item, 15);
                    fill(item, 16);
                    fill(item, 17);
                    fill(item, 18);
                    fill(item, 19);
                    fill(item, 20);
                    fill(item, 21);
                    fill(item, 22);
                    fill(item, 23);
                    fill(item, 24);
                    fill(item, 25);
                    fill(item, 26);
                    fill(item, 27);
                    fill(item, 28);
                    fill(item, 29);
                    fill(item, 30);
                    fill(item, 31);
                }
                reportList = reportList.DistinctBy(a => a.eName).ToList();
                int count = 0;//报晚餐次数
                int noeatCount = 0; //报晚餐不吃次数
                foreach (var item in reportList)
                {
                    count = 0;
                    noeatCount = 0;
                    item.dinnerCost = 5;
                    #region 获取需要收费晚餐次数
                    if (item.day1 == "√")
                    {
                        count++;
                    }
                    if (item.day2 == "√")
                    {
                        count++;
                    }
                    if (item.day3 == "√")
                    {
                        count++;
                    }
                    if (item.day4 == "√")
                    {
                        count++;
                    }
                    if (item.day5 == "√")
                    {
                        count++;
                    }
                    if (item.day6 == "√")
                    {
                        count++;
                    }
                    if (item.day7 == "√")
                    {
                        count++;
                    }
                    if (item.day8 == "√")
                    {
                        count++;
                    }
                    if (item.day9 == "√")
                    {
                        count++;
                    }
                    if (item.day10 == "√")
                    {
                        count++;
                    }
                    if (item.day11 == "√")
                    {
                        count++;
                    }
                    if (item.day12 == "√")
                    {
                        count++;
                    }
                    if (item.day13 == "√")
                    {
                        count++;
                    }
                    if (item.day14 == "√")
                    {
                        count++;
                    }
                    if (item.day15 == "√")
                    {
                        count++;
                    }
                    if (item.day16 == "√")
                    {
                        count++;
                    }
                    if (item.day17 == "√")
                    {
                        count++;
                    }
                    if (item.day18 == "√")
                    {
                        count++;
                    }
                    if (item.day19 == "√")
                    {
                        count++;
                    }
                    if (item.day20 == "√")
                    {
                        count++;
                    }
                    if (item.day21 == "√")
                    {
                        count++;
                    }
                    if (item.day22 == "√")
                    {
                        count++;
                    }
                    if (item.day23 == "√")
                    {
                        count++;
                    }
                    if (item.day24 == "√")
                    {
                        count++;
                    }
                    if (item.day25 == "√")
                    {
                        count++;
                    }
                    if (item.day26 == "√")
                    {
                        count++;
                    }
                    if (item.day27 == "√")
                    {
                        count++;
                    }
                    if (item.day28 == "√")
                    {
                        count++;
                    }
                    if (item.day29 == "√")
                    {
                        count++;
                    }
                    if (item.day30 == "√")
                    {
                        count++;
                    }
                    if (item.day31 == "√")
                    {
                        count++;
                    }
                    #endregion
                    #region 获取报晚餐不吃次数
                    if (item.day1 == "○")
                    {
                        noeatCount++;
                    }
                    if (item.day2 == "○")
                    {
                        noeatCount++;
                    }
                    if (item.day3 == "○")
                    {
                        noeatCount++;
                    }
                    if (item.day4 == "○")
                    {
                        noeatCount++;
                    }
                    if (item.day5 == "○")
                    {
                        noeatCount++;
                    }
                    if (item.day6 == "○")
                    {
                        noeatCount++;
                    }
                    if (item.day7 == "○")
                    {
                        noeatCount++;
                    }
                    if (item.day8 == "○")
                    {
                        noeatCount++;
                    }
                    if (item.day9 == "○")
                    {
                        noeatCount++;
                    }
                    if (item.day10 == "○")
                    {
                        noeatCount++;
                    }
                    if (item.day11 == "○")
                    {
                        noeatCount++;
                    }
                    if (item.day12 == "○")
                    {
                        noeatCount++;
                    }
                    if (item.day13 == "○")
                    {
                        noeatCount++;
                    }
                    if (item.day14 == "○")
                    {
                        noeatCount++;
                    }
                    if (item.day15 == "○")
                    {
                        noeatCount++;
                    }
                    if (item.day16 == "○")
                    {
                        noeatCount++;
                    }
                    if (item.day17 == "○")
                    {
                        noeatCount++;
                    }
                    if (item.day18 == "○")
                    {
                        noeatCount++;
                    }
                    if (item.day19 == "○")
                    {
                        noeatCount++;
                    }
                    if (item.day20 == "○")
                    {
                        noeatCount++;
                    }
                    if (item.day21 == "○")
                    {
                        noeatCount++;
                    }
                    if (item.day22 == "○")
                    {
                        noeatCount++;
                    }
                    if (item.day23 == "○")
                    {
                        noeatCount++;
                    }
                    if (item.day24 == "○")
                    {
                        noeatCount++;
                    }
                    if (item.day25 == "○")
                    {
                        noeatCount++;
                    }
                    if (item.day26 == "○")
                    {
                        noeatCount++;
                    }
                    if (item.day27 == "○")
                    {
                        noeatCount++;
                    }
                    if (item.day28 == "○")
                    {
                        noeatCount++;
                    }
                    if (item.day29 == "○")
                    {
                        noeatCount++;
                    }
                    if (item.day30 == "○")
                    {
                        noeatCount++;
                    }
                    if (item.day31 == "○")
                    {
                        noeatCount++;
                    }
                    #endregion
                    item.count = count;
                    item.noeatcount = noeatCount;
                    item.totalnoEatCost = noeatCount * Convert.ToDecimal(commonInstance.GetConfig().voluntarily);
                    item.totalCost = item.count * Convert.ToDecimal(commonInstance.GetConfig().DinnerCost) + noeatCount * Convert.ToDecimal(commonInstance.GetConfig().voluntarily);
                }
                GetDinnerCostReportOutput fill(GetDinnerCostReportOutput dao, int day)
                {
                    var model = list.Where(x => x.FEID == dao.eId && x.FRTime == startTime.AddDays(day - 1)).FirstOrDefault();
                    string type = string.Empty;

                    if (model == null)
                    {
                        type = "";
                    }
                    else if (model.FWorkOver)
                    {
                        type = "加";
                    }
                    else
                    {
                        type = "√";
                    }
                    if (model != null)
                    {
                        var signModel = _SignIn.GetFirst(x => x.FEId == dao.eId && x.FRId == model.Id);
                        if (signModel == null)
                        {
                            type = "○";
                        }
                    }
                    switch (day)
                    {
                        case 1:
                            dao.day1 = type;
                            break;
                        case 2:
                            dao.day2 = type;
                            break;
                        case 3:
                            dao.day3 = type;
                            break;
                        case 4:
                            dao.day4 = type;
                            break;
                        case 5:
                            dao.day5 = type;
                            break;
                        case 6:
                            dao.day6 = type;
                            break;
                        case 7:
                            dao.day7 = type;
                            break;
                        case 8:
                            dao.day8 = type;
                            break;
                        case 9:
                            dao.day9 = type;
                            break;
                        case 10:
                            dao.day10 = type;
                            break;
                        case 11:
                            dao.day11 = type;
                            break;
                        case 12:
                            dao.day12 = type;
                            break;
                        case 13:
                            dao.day13 = type;
                            break;
                        case 14:
                            dao.day14 = type;
                            break;
                        case 15:
                            dao.day15 = type;
                            break;
                        case 16:
                            dao.day16 = type;
                            break;
                        case 17:
                            dao.day17 = type;
                            break;
                        case 18:
                            dao.day18 = type;
                            break;
                        case 19:
                            dao.day19 = type;
                            break;
                        case 20:
                            dao.day20 = type;
                            break;
                        case 21:
                            dao.day21 = type;
                            break;
                        case 22:
                            dao.day22 = type;
                            break;
                        case 23:
                            dao.day23 = type;
                            break;
                        case 24:
                            dao.day24 = type;
                            break;
                        case 25:
                            dao.day25 = type;
                            break;
                        case 26:
                            dao.day26 = type;
                            break;
                        case 27:
                            dao.day27 = type;
                            break;
                        case 28:
                            dao.day28 = type;
                            break;
                        case 29:
                            dao.day29 = type;
                            break;
                        case 30:
                            dao.day30 = type;
                            break;
                        case 31:
                            dao.day31 = type;
                            break;
                    }
                    return dao;
                }
                return result.Success(reportList);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("MealReportingController-RepEdtstatistics:" + ex);
                return result.Exception();
            }
        }

        /// <summary>
        /// 更改数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<string>> EditData(EditDataInput input)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                if (string.IsNullOrWhiteSpace(input.eName))
                {
                    return result.Error("请输入姓名");
                }
                string eName = input.eName;
                string eid = input.eId;
                string eEngName = input.eEngName;
                if (eid == "0")
                {
                    var autoModel = _AutoM.GetFirst(x => x.FEName == eName || x.FEEngName == eName);
                    if (autoModel != null)
                    {
                        eName = autoModel.FEName;
                        eEngName = autoModel.FEEngName;
                        eid = autoModel.FEId;
                    }
                    else
                    {
                        return result.Error("找不到该人员!");
                    }
                }

                tSignIn signModel = new tSignIn();
                tMealReporting repModel = new tMealReporting();
                repModel = _MealReporting.GetFirst(x => x.FEID == eid && !x.FDeleted && !x.FIsOdd && x.FEName == eName && x.FMType == input.MType && x.FRTime == DateTime.Parse(input.CreateTime).Date);
                switch (input.EType)
                {
                    //补签到记录
                    case 1:
                        string rid = repModel == null ? "0" : repModel.Id;
                        signModel = _SignIn.GetFirst(x => x.FRId == rid && x.FEId == eid && x.FEName == eName);
                        if (signModel == null)
                        {
                            _SignIn.Insert(new tSignIn
                            {
                                CreatorId = CurrentUserId,
                                CreateTime = DateTime.Parse(input.CreateTime),
                                FRId = rid,
                                FEEngName = eEngName,
                                FEId = eid,
                                FEName = eName,
                            });
                        }
                        break;
                    //补报餐记录
                    case 2:
                        _MealReporting.Insert(new tMealReporting
                        {
                            FMType = input.MType,
                            FEID = eid,
                            FEEngName = eEngName,
                            FEName = eName,
                            CreateTime = DateTime.Parse(input.CreateTime),
                            FCancellation = false,
                            FCancelReason = "",
                            FCancelTime = DateTime.MinValue,
                            CreatorId = CurrentUserId,
                            FDeptName = "",
                            FDeleted = false,
                            FRTime = DateTime.Parse(input.CreateTime).Date,
                            FWorkOver = input.WorkOver,
                            FIsOverTime = false,
                            FReportingType = 3,
                            FIsOdd = false,
                        });
                        break;
                    case 3:
                        repModel.FWorkOver = input.WorkOver;
                        _MealReporting.Update(repModel);
                        break;
                    case 4:
                        repModel.FDeleted = true;
                        _MealReporting.Update(repModel);
                        break;
                    default:
                        break;
                }
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("MealReportingController-EditData:" + ex);
                return result.Exception();
            }
        }

        [HttpPost]
        public async Task<ResultMsg<string>> ExportRepeatstatistics(RepstatisticsInput input)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                var exp = Expressionable.Create<tSignIn>();
                if (!string.IsNullOrWhiteSpace(input.Name))
                {
                    exp.And(m => m.FEName.Contains(input.Name));
                }
                exp.And(x => x.CreateTime >= input.StartDate && x.CreateTime <= input.EndDate);
                var count = _SignIn.GetList(exp.ToExpression()).Count();
                var signList = _SignIn.GetList(exp.ToExpression()).OrderByDescending(c => c.CreateTime).ToList();
                List<EdtstatisticsOutput> list = new List<EdtstatisticsOutput>();
                var exp2 = Expressionable.Create<tMealReporting>();

                var mealList = _MealReporting.GetList(exp2.ToExpression());
                EdtstatisticsOutput dao = new EdtstatisticsOutput();
                foreach (var item in signList)
                {
                    dao = new EdtstatisticsOutput();
                    dao.Rep = item.FRId == "0" ? "否" : "是";
                    if (item.FRId.Length > 0)
                    {
                        var FType = mealList.Where(x => x.Id == item.FRId).FirstOrDefault()?.FMType;
                        dao.FType = FType == 1 ? "午餐" : "晚餐";
                    }
                    else
                    {
                        var hour = item.CreateTime.Hour;
                        if (hour >= 11 && hour <= 14)
                        {
                            dao.FType = "午餐";
                        }
                        else if (hour >= 17 && hour <= 20)
                        {
                            dao.FType = "晚餐";
                        }
                    }
                    dao.Name = item.FEName;
                    dao.STime = item.CreateTime;
                    dao.RDate = item.CreateTime.ToString("yyyy-MM-dd");
                    list.Add(dao);
                }
                if (input.EatType == 1)
                {
                    list = list.Where(x => x.Rep == "是").ToList();
                }
                else if (input.EatType == 2)
                {
                    list = list.Where(x => x.Rep == "否").ToList();
                }
                if (input.Type != 0)
                {
                    string FType = input.Type == 1 ? "午餐" : "晚餐";
                    list = list.Where(x => x.FType == FType).ToList();
                }

                string physicalPath = _webHostEnvironment.WebRootPath;
                long timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
                string path = physicalPath + "\\Execl\\" + timestamp + ".xlsx";

                // 创建Excel工作簿和工作表  
                var workbook = new XSSFWorkbook();
                var sheet = workbook.CreateSheet("Sheet1");

                // 创建表头行  
                var headerRow = sheet.CreateRow(0);
                headerRow.CreateCell(0).SetCellValue("日期");
                headerRow.CreateCell(1).SetCellValue("姓名");
                headerRow.CreateCell(2).SetCellValue("午餐/晚餐");
                headerRow.CreateCell(3).SetCellValue("签到时间");
                headerRow.CreateCell(4).SetCellValue("是否报餐");

                // 创建数据行  
                for (int i = 0; i < list.Count; i++)
                {
                    var dataRow = sheet.CreateRow(i + 1);
                    dataRow.CreateCell(0).SetCellValue(list[i].RDate);
                    dataRow.CreateCell(1).SetCellValue(list[i].Name);
                    dataRow.CreateCell(2).SetCellValue(list[i].FType);
                    dataRow.CreateCell(3).SetCellValue(list[i].STime.ToString());
                    dataRow.CreateCell(4).SetCellValue(list[i].Rep);
                    // ... 添加更多的数据列  
                }
                // 保存Excel文件  
                using (FileStream fileStream = new FileStream(path, FileMode.Create))
                {
                    workbook.Write(fileStream);
                }
                return result.Success(timestamp + ".xlsx");
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("MealReportingController-Edtstatistics:" + ex);
                return result.Exception();
            }
        }
        /// <summary>
        /// 导出报餐人员导出情况
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<string>> ExportRepEdtstatistics(RepstatisticsInput input)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                var exp = Expressionable.Create<tMealReporting>();
                exp.And(m => m.FDeleted == false && m.FRTime >= input.StartDate && m.FRTime <= input.EndDate);
                if (!string.IsNullOrWhiteSpace(input.Name))
                {
                    exp.And(m => m.FEName.Contains(input.Name));
                }
                if (input.Type != 0)
                {
                    exp.And(m => m.FMType == input.Type);
                }
                var list = _db.Queryable<tMealReporting>()
                     .LeftJoin<tSignIn>((m, s) => m.FEID == s.FEId && m.Id == s.FRId)
                     .Where(exp.ToExpression()).Distinct()
                     .OrderByDescending((m, s) => s.CreateTime)
                     .Select((m, s) => new RepEdtstatisticsOutput
                     {
                         RepTime = m.FRTime.ToString("yyyy-MM-dd"),
                         Rtime = m.CreateTime,
                         Stime = s.CreateTime,
                         Type = m.FMType == 1 ? "午餐" : "晚餐",
                         Name = m.FEName,
                         IsCancel = m.FCancellation ? "是" : "否",
                         CTime = m.FCancelTime,
                         CancelReason = m.FCancelReason,
                     }).ToList();
                if (input.EatType == 1)
                {
                    list = list.Where(x => x.Stime == null).ToList();
                }
                else if (input.EatType == 2)
                {
                    list = list.Where(x => x.Stime != null).ToList();
                }


                string physicalPath = _webHostEnvironment.WebRootPath;
                long timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
                string path = physicalPath + "\\Execl\\" + timestamp + ".xlsx";

                // 创建Excel工作簿和工作表  
                var workbook = new XSSFWorkbook();
                var sheet = workbook.CreateSheet("Sheet1");

                // 创建表头行  
                var headerRow = sheet.CreateRow(0);
                headerRow.CreateCell(0).SetCellValue("报餐日期");
                headerRow.CreateCell(1).SetCellValue("报餐时间");
                headerRow.CreateCell(2).SetCellValue("签到日期");
                headerRow.CreateCell(3).SetCellValue("午餐/晚餐");
                headerRow.CreateCell(4).SetCellValue("报餐人");
                headerRow.CreateCell(5).SetCellValue("是否取消");
                headerRow.CreateCell(6).SetCellValue("取消时间");
                headerRow.CreateCell(7).SetCellValue("取消原因");

                // 创建数据行  
                for (int i = 0; i < list.Count; i++)
                {
                    var dataRow = sheet.CreateRow(i + 1);
                    dataRow.CreateCell(0).SetCellValue(list[i].RepTime.ToString());
                    dataRow.CreateCell(1).SetCellValue(list[i].Rtime.ToString());
                    dataRow.CreateCell(2).SetCellValue(list[i].Stime == null ? "" : list[i].Stime.ToString());
                    dataRow.CreateCell(3).SetCellValue(list[i].Type);
                    dataRow.CreateCell(4).SetCellValue(list[i].Name);
                    dataRow.CreateCell(5).SetCellValue(list[i].IsCancel);
                    dataRow.CreateCell(6).SetCellValue(list[i].CTime == null ? "" : list[i].CTime.ToString());
                    dataRow.CreateCell(7).SetCellValue(list[i].CancelReason);
                    // ... 添加更多的数据列  
                }
                // 保存Excel文件  
                using (FileStream fileStream = new FileStream(path, FileMode.Create))
                {
                    workbook.Write(fileStream);
                }
                return result.Success(timestamp + ".xlsx");
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("MealReportingController-RepEdtstatistics:" + ex);
                return result.Exception();
            }
        }

        [HttpPost]
        [AllowAnonymous]
        public IActionResult ExportExcel()
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    string currentPath = HttpContext.Request.Path.Value;
                    string physicalPath = _webHostEnvironment.WebRootPath;
                    long timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
                    // 获取数据，这里假设从数据库中获取数据  
                    string path = physicalPath + "\\" + timestamp + ".xls";
                    var data = _CanteenMenu.GetList();
                    // 创建Excel工作簿和工作表  
                    var workbook = new XSSFWorkbook();
                    var sheet = workbook.CreateSheet("Sheet1");

                    // 创建表头行  
                    var headerRow = sheet.CreateRow(0);
                    headerRow.CreateCell(0).SetCellValue("Column1");
                    headerRow.CreateCell(1).SetCellValue("Column2");
                    // ... 添加更多的表头列  

                    // 创建数据行  
                    for (int i = 0; i < data.Count; i++)
                    {
                        var dataRow = sheet.CreateRow(i + 1);
                        dataRow.CreateCell(0).SetCellValue(data[i].FMName);
                        dataRow.CreateCell(1).SetCellValue(data[i].FMName2);
                        // ... 添加更多的数据列  
                    }
                    //// 保存Excel文件  
                    //using (FileStream fileStream = new FileStream(path, FileMode.Create))
                    //{
                    //    workbook.Write(fileStream);
                    //}

                    // 将Excel保存到内存中  
                    workbook.Write(memoryStream);
                    memoryStream.Position = 0;
                    // 返回Excel文件作为下载响应  
                    return File(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Export.xlsx");
                }

            }
            catch (Exception ex)
            {

                throw;
            }
        }
    }
}
